<?php

namespace frontend\modules\Api\controllers;

use common\models\StockBalance;
use common\models\StockBalanceDetail;
use common\models\StockProduct;
use common\models\StockRecord;
use common\models\SysSetting;
use common\models\TallyAccount;
use common\models\TallyCategory;
use common\models\TallyRecord;
use common\models\TallyStore;
use common\services\TallyCategoryService;
use common\services\TallyProductStockCaseServices;
use common\services\TallyStockBalanceService;
use common\services\TallyStockProductService;
use frontend\modules\Dao\TallyRecordDao;
use Yii;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;

class EarchtsController extends ApiController
{
    /**
     * @return array
     * 引入行为验证 过滤授权
     */
    public function behaviors()
    {
        $config = [
            'access' => [
                'class' => AccessControl::className(),
                'denyCallback' => function($rule, $action){
                    return self::failureResponse(100001, '请先登录!',[]);
                },
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ]
                ]
            ],
        ];
        return ArrayHelper::merge(parent::behaviors(), $config);
    }


    /**
     * @throws
     * 分类列表
     */
    public function actionLiRuns()
    {
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $condition = Yii::$app->getRequest()->get();
        $category_id = TallyRecordDao::get_builder($condition)
            ->select(['category_id','category_name'])
            ->groupBy(['category_id','category_name'])->andFilterWhere([
                '<>','category_id',0
            ])->asArray()->all();
        $lists_data_shou = [

        ];
        $lists_data_zhi = [

        ];
        $shourus = 0;
        $zhichus = 0;
        $liruns = 0;
        foreach ($category_id as $value){
            $shouru = TallyRecordDao::get_builder($condition)->andFilterWhere([
                'category_id'=>$value['category_id'],
                'type'=>10,
            ])->sum('amount');

            $zhichu = TallyRecordDao::get_builder($condition)->andFilterWhere([
                'category_id'=>$value['category_id'],
                'type'=>20,
            ])->sum('amount');

            if(!is_null($shouru)){
                $lists_data_shou[] = [
                    'category_name'=>$value['category_name'],
                    'nums'=>$shouru
                ];
                $liruns = bcadd($liruns,$shouru,2);
                $shourus = bcadd($shouru,$shourus,2);
            }else{
                $lists_data_zhi[] = [
                    'category_name'=>$value['category_name'],
                    'nums'=>$zhichu
                ];
                $liruns = bcsub($liruns,$zhichu,2);
                $zhichus = bcadd($zhichu,$zhichus,2);
            }

        }
        return self::successResponse([
            'zhichu'=>$lists_data_zhi,
            'shouru'=>$lists_data_shou,
            'lirun'=>$liruns,
            'shourus'=>$shourus,
            'zhichus'=>$zhichus,
        ]);
    }


    public function actionLiRunJi(){
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $year = Yii::$app->getRequest()->get('year').'-';
        $condifition = Yii::$app->getRequest()->get();
        $dates = [
            [
                'begin_date'=>$year.'01-01 00:00:00',
                'end_date'=>$year.'03-31 23:59:59',
                'tally_id'=>$tallyId,
                'name'=>'第一季度'
            ],
            [
                'begin_date'=>$year.'04-01 00:00:00',
                'end_date'=>$year.'06-30 23:59:59',
                'tally_id'=>$tallyId,
                'name'=>'第二季度'
            ],
            [
                'begin_date'=>$year.'07-01 00:00:00',
                'end_date'=>$year.'09-30 23:59:59',
                'tally_id'=>$tallyId,
                'name'=>'第三季度'
            ],
            [
                'begin_date'=>$year.'10-01 00:00:00',
                'end_date'=>$year.'12-31 23:59:59',
                'tally_id'=>$tallyId,
                'name'=>'第四季度'
            ],

        ];

        foreach ($dates as &$value){
            if($this->checkIsHasField($condifition,'tag_name')){
                $value['tag_name'] = $condifition['tag_name'];
            }
            $shouru = TallyRecordDao::get_builder($value)->andFilterWhere([
                'type'=>10,
            ])->sum('amount');

            $zhichu = TallyRecordDao::get_builder($value)->andFilterWhere([
                'type'=>20,
            ])->sum('amount');

            if(!is_null($shouru)){
                $value['s_r'] = $shouru;
            }else{
                $value['s_r'] = '0.00';
            }

            if(!is_null($zhichu)){
                $value['z_c'] = $zhichu;
            }else{
                $value['z_c'] = '0.00';

            }

            $value['l_r'] = bcsub($value['s_r'],$value['z_c'],2);
        }
        return self::successResponse([
            'datas'=>$dates,
            'zong'=>bcsub(array_sum(array_column($dates,'l_r')),0.00,2)
        ]);

    }





    public function actionProjectsLiRun(){
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $condition  = Yii::$app->getRequest()->get();

        //查询项目并且分组
        $project_ids = TallyRecordDao::get_builder($condition);

        if(self::checkIsHasField($condition,'project_type')){
            $project_ids
                ->andFilterWhere(['<>','project_id',0])->select(['project_id','project_name'])
                ->groupBy(['project_id','project_name']);
        }else if(self::checkIsHasField($condition,'member_type')){
            $project_ids
                ->andFilterWhere(['<>','member_id',0])->select(['member_id','member_name'])
                ->groupBy(['member_id','member_name']);
        }else if(self::checkIsHasField($condition,'store_type')){
            $project_ids
                ->andFilterWhere(['<>','store_id',0])->select(['store_id','store_name'])
                ->groupBy(['store_id','store_name']);
        }
        $project_ids = $project_ids->asArray()->all();;

        $datas = [];
        //利润
        foreach ($project_ids as &$value){
            $s_r = TallyRecordDao::get_builder($condition);

            if(self::checkIsHasField($condition,'project_type')){
                $s_r->andFilterWhere([
                    'project_id'=>$value['project_id'],
                    'type'=>10,
                ]);
            }else if(self::checkIsHasField($condition,'member_type')){
                $s_r->andFilterWhere([
                    'member_id'=>$value['member_id'],
                    'type'=>10,
                ]);
            }else if(self::checkIsHasField($condition,'store_type')){
                $s_r->andFilterWhere([
                    'store_id'=>$value['store_id'],
                    'type'=>10,
                ]);
            }

             $s_r  = $s_r->sum('amount');



            $z_c = TallyRecordDao::get_builder($condition);

            if(self::checkIsHasField($condition,'project_type')){
                $z_c->andFilterWhere([
                    'project_id'=>$value['project_id'],
                    'type'=>20,
                ]);
            }else if(self::checkIsHasField($condition,'member_type')){
                $z_c->andFilterWhere([
                    'member_id'=>$value['member_id'],
                    'type'=>20,
                ]);
            }else if(self::checkIsHasField($condition,'store_type')){
                $z_c->andFilterWhere([
                    'store_id'=>$value['store_id'],
                    'type'=>20,
                ]);
            }
            $z_c = $z_c->sum('amount');
            $l_r = bcsub($s_r,$z_c,2);
            $zong = bcadd($s_r,$z_c,2);
            $itemData = [
                's_r'=>is_null($s_r) ? 0 : $s_r,
                'z_c'=>is_null($z_c) ? 0 : $z_c,
                'l_r'=>$l_r,
                'zong'=>$zong,
            ];
            if($this->checkIsHasField($condition,'project_type')){
                $itemData = array_merge([
                    'project_id'=>$value['project_id'],
                    'project_name'=>$value['project_name'],
                ],$itemData);
            }else if(self::checkIsHasField($condition,'member_type')){
                $itemData = array_merge([
                    'member_id'=>$value['member_id'],
                    'member_name'=>$value['member_name'],
                ],$itemData);
            }else if(self::checkIsHasField($condition,'store_type')){
                $itemData = array_merge([
                    'store_id'=>$value['store_id'],
                    'store_name'=>$value['store_name'],
                ],$itemData);
            }
            $datas[] = $itemData;
        }
        return self::successResponse($datas);
    }






    public function actionProjectsShouFuKuan(){
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $condition  = Yii::$app->getRequest()->get();
        //查询项目并且分组
        $project_ids = TallyRecordDao::get_builder($condition);

        if(self::checkIsHasField($condition,'project_type')){
            $project_ids
                ->andFilterWhere(['<>','project_id',0])
                ->select(['project_id','project_name'])
                ->groupBy(['project_id','project_name']);
        }else if(self::checkIsHasField($condition,'member_type')){
            $project_ids
                ->andFilterWhere(['<>','member_id',0])
                ->select(['member_id','member_name'])
                ->groupBy(['member_id','member_name']);
        }else if(self::checkIsHasField($condition,'store_type')){
            $project_ids
                ->andFilterWhere(['<>','store_id',0])
                ->select(['store_id','store_name'])
                ->groupBy(['store_id','store_name']);
        }

        $project_ids = $project_ids->asArray()->all();



        $datas = [

        ];

        //利润
        foreach ($project_ids as &$value){
            $s_r = TallyRecordDao::get_builder($condition);

            if(self::checkIsHasField($condition,'project_type')){
                $s_r->andFilterWhere([
                    'category_id'=>98,
                    'project_id'=>$value['project_id'],
                    'type'=>10,
                ]);
            }else if(self::checkIsHasField($condition,'member_type')){
                $s_r->andFilterWhere([
                    'category_id'=>98,
                    'member_id'=>$value['member_id'],
                    'type'=>10,
                ]);
            }else if(self::checkIsHasField($condition,'store_type')){
                $s_r->andFilterWhere([
                    'category_id'=>98,
                    'store_id'=>$value['store_id'],
                    'type'=>10,
                ]);
            }

            $s_r  = $s_r->sum('amount');



            $z_c = TallyRecordDao::get_builder($condition);

            if(self::checkIsHasField($condition,'project_type')){
                $z_c->andFilterWhere([
                    'category_id'=>99,
                    'project_id'=>$value['project_id'],
                    'type'=>20,
                ]);
            }else if(self::checkIsHasField($condition,'member_type')){
                $z_c->andFilterWhere([
                    'category_id'=>99,
                    'member_id'=>$value['member_id'],
                    'type'=>20,
                ]);
            }else if(self::checkIsHasField($condition,'store_type')){
                $z_c->andFilterWhere([
                    'category_id'=>99,
                    'store_id'=>$value['store_id'],
                    'type'=>20,
                ]);
            }
            $z_c = $z_c->sum('amount');
            $l_r = bcsub($s_r,$z_c,2);
            $zong = bcadd($s_r,$z_c,2);
            $itemData = [
                's_r'=>is_null($s_r) ? 0 : $s_r,
                'z_c'=>is_null($z_c) ? 0 : $z_c,
                'l_r'=>$l_r,
                'zong'=>$zong,
            ];
            if($this->checkIsHasField($condition,'project_type')){
                $itemData = array_merge([
                    'project_id'=>$value['project_id'],
                    'project_name'=>$value['project_name']
                ],$itemData);
            }else if(self::checkIsHasField($condition,'member_type')){
                $itemData = array_merge([
                    'member_id'=>$value['member_id'],
                    'member_name'=>$value['member_name'],
                ],$itemData);
            }else if(self::checkIsHasField($condition,'store_type')){
                $itemData = array_merge([
                    'store_id'=>$value['store_id'],
                    'store_name'=>$value['store_name'],
                ],$itemData);
            }
            $datas[] = $itemData;
        }
        return self::successResponse($datas);
    }







    public function actionCaiGouGoods(){
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $condition = Yii::$app->getRequest()->get();
        $query = StockRecord::find();
        if(self::checkIsHasField($condition,'begin_date_start_yue')){
            $query->andFilterWhere(['>=','tally_date',$condition['begin_date_start_yue'].'-01']);
            $query->andFilterWhere(['<','tally_date',date('Y-m-d',strtotime('+1month',strtotime($condition['begin_date_start_yue'].'-01')))]);
        }

        $query->andFilterWhere([
            'tally_id'=>$tallyId,
            'sales_type'=>$condition['sales_type']
        ]);

        $list = $query->orderBy('tally_date desc,created_time DESC')->asArray()->all();
        foreach ($list as $lk =>  $lv) {
            $list[$lk]['product_detail'] = json_decode($lv['product_detail'],true);
            $list[$lk]['sales_type_str'] = StockRecord::getOptStr($lv['sales_type']);
            $list[$lk]['state_txt'] = StockRecord::getStateStr($lv['state']);
        }


        $datas_return = [];
        $week_str = ['周日','周一','周二','周三','周四','周五','周六'];
        foreach ($list as $lk =>  $lv) {
            $product_detail = $lv['product_detail'];
            unset($lv['product_detail']);
            foreach ($product_detail as $value){
                $itemValue = $value;
                $itemValue['orders_info'] = $lv;
                $itemValue['date_day'] = date('d',strtotime($lv['tally_date']));
                $itemValue['date_week_str'] = $week_str[date('w',strtotime($lv['tally_date']))];
                $datas_return[] = $itemValue;
            }
        }
        return  self::successResponse([
            'datas'=>$datas_return,
            'all_count'=>bcadd(array_sum(array_column($list,'total_num')),0,2),
            'all_money'=>bcadd(array_sum(array_column($list,'total_money')),0,2),
        ]);
    }






    public function actionInOutStock(){

        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $condition = Yii::$app->getRequest()->get();
        $stockQyery = StockBalanceDetail::find()->andFilterWhere([
            '=','tally_id',$tallyId
        ]);
        //筛选月份
        if(self::checkIsHasField($condition,'begin_date_start_yue')){
            $stockQyery->andFilterWhere(['>=','tally_date',$condition['begin_date_start_yue'].'-01']);
            $stockQyery->andFilterWhere(['<','tally_date',date('Y-m-d',strtotime('+1month',strtotime($condition['begin_date_start_yue'].'-01')))]);
        }
        $file_str = ['in_num','out_num'];
        if(self::checkIsHasField($condition,'type_net')){
            $stockQyery->andFilterWhere(['>',$file_str[$condition['type_net']],0]);
        }

        if(self::checkIsHasField($condition,'house_id')){
            $stockQyery->andFilterWhere(['=','house_id',$condition['house_id']]);
        }


        if(self::checkIsHasField($condition,'is_group')){
            $stockQyery->groupBy('product_id');
            $stockQyery->select("sum(balance_money) as prices,sum(".$file_str[$condition['type_net']].") as counts,product_id");
        }

        //是否采购相关
        if(self::checkIsHasField($condition,'is_cai')){
            //采购订单IN
            $stockQyery->andFilterWhere([
                '<>','stock_record_id',0
            ]);
        }


        $datas = $stockQyery->asArray()->all();
        foreach ($datas as &$value){
            $product = StockProduct::find()
                ->select('*')
                ->where(['id'=>$value['product_id']])
                ->asArray()
                ->limit(1)
                ->one();
            $value['title'] = $product['title'];
            $value['unit'] = $product['unit'];
            $value['memo'] = $product['memo'];
        }
        return  self::successResponse([
            'datas'=>$datas,
            'prices'=>bcadd(array_sum(array_column($datas,'prices')),0,2),
            'counts'=>bcadd(array_sum(array_column($datas,'counts')),0,2),
        ]);
    }



    public function actionGetStockBalance(){
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $condition = Yii::$app->getRequest()->get();
        //获取指定账本
        $query = StockBalanceDetail::find()->where([
            'tally_id'=>$tallyId,
        ]);
        //根据月份排序
        if(self::checkIsHasField($condition,'begin_date_start_yue')){
            $query->andFilterWhere(['>=','tally_date',$condition['begin_date_start_yue'].'-01']);
            $query->andFilterWhere(['<','tally_date',date('Y-m-d',strtotime('+1month',strtotime($condition['begin_date_start_yue'].'-01')))]);
        }
        if(self::checkIsHasField($condition,'type')){
            //销量(数量)
            if($condition['type'] == 0){
                $query->andFilterWhere([
                    '>','out_num',0
                ])->select('sum(out_num) as values,product_id')->orderBy('values desc');
            }else if($condition['type'] == 1){
                $query->andFilterWhere([
                    '>','out_num',0
                ])->select('sum(balance_money) as values,product_id')->orderBy('values desc');
            }
            $query->groupBy('product_id');
        }
        $datas = $query->asArray()->all();
        foreach ($datas as $key => &$value){
            $product = StockProduct::find()
                ->select('*')
                ->where(['id'=>$value['product_id']])
                ->asArray()
                ->limit(1)
                ->one();
            $value['title'] = $product['title'];
            $value['index'] = ($key+1);
        }
        return  self::successResponse($datas);
    }



    public function actionKeHuCounts(){
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $condition = Yii::$app->getRequest()->get();
        //获取采购单子
        $stock_query = StockRecord::find()->where([
            'tally_id'=>$tallyId
        ])->andFilterWhere([
            '<>','store_id',0
        ]);

        if(self::checkIsHasField($condition,'begin_date_start_yue')){
            $stock_query->andFilterWhere(['>=','tally_date',$condition['begin_date_start_yue'].'-01']);
            $stock_query->andFilterWhere(['<','tally_date',date('Y-m-d',strtotime('+1month',strtotime($condition['begin_date_start_yue'].'-01')))]);
        }

        if(self::checkIsHasField($condition,'type')){
            //销量(数量)
            if($condition['type'] == 0){
                $stock_query
                    ->andFilterWhere([
                        '=','sales_type',10
                    ])
                    ->select('sum(total_num) as values,store_id')
                    ->orderBy('values desc');
            }else if($condition['type'] == 1){
                $stock_query
                    ->andFilterWhere([
                        '=','sales_type',10
                    ])
                    ->select('sum(total_money) as values,store_id')
                    ->orderBy('values desc');
             }
            $stock_query->groupBy('store_id');
        }
        $datas = $stock_query->asArray()->all();
        foreach ($datas as $key => &$value){
            $tally = TallyStore::find()->where([
                'tally_id'=>$tallyId,
                'id'=>$value['store_id']
            ])->one();
            $value['store_name'] = $tally['title'];
            $value['index'] = ($key+1);
        }
        return self::successResponse($datas);

    }




}